#! /usr/bin/python
"""
 Module: createplot.py

 Ver 0.8.0
 Original Release: 01/02/2009

 Rev 0.9.2; Last: 03/12/2013 - Previous: 03/11/2013 (AEM)
   - Reconfigure, fuonctionalize
   - 

 Command line utility to create the plot files from a readmeter.py
 log file to feed gnuplot.

 This file is part of the DMM Reader project.

 Copyright (C) 2012-2013  Arnold E. Morgan

    DMM Reader is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""

# *** System Modules ***
import os
import sys

# *** Custom Modules ***
import plotcfg
import plotutils


def plot_main():
   """ Match up the template file with the measurement values. 

   Config replacment values come from the config file and are assigend to the
   InitValues dictionary. Calculated values are then added to the InitValues
   dictionary. A new sesson template file is create from those values.
   """

   # Ensure default location is set to installation directory.
   PlotPath = os.path.dirname(os.path.abspath(sys.argv[0]))

   ParentDir = ""       # Log and cfg files should be located here.
   thisDir = ""
   # Log and cfg files are assumed to be located one directory level up.
   (ParentDir, thisDir) = os.path.split(PlotPath)

   Debug = False
   RtnMssg = ""
   RtnStat = 0
   FailFlag = False

   (RtnStat, InitValues) = plotcfg.GetCfgSettings(ParentDir)
   if not RtnStat:
      print "Config file read failed"
      FailFlag = True
   else:
      print "\nInitValues dictionary:"
      print "_" * 50
      keylist = InitValues.keys()
      keylist.sort()
      for keyval in keylist:
         print "%-25s   %-s" % (keyval, InitValues[keyval])

   if not FailFlag:
      (RtnStat, SessionTemplate, RtnMssg) = plotutils.read_template(PlotPath, InitValues['Template'])
      if  not RtnStat:
         print RtnMssg
         sys.exit()

      (RtnState, SessionLog, RtnMssg) = plotutils.read_log(ParentDir, InitValues['LogFileName'])

      if not RtnState:
         print RtnMssg
      else:
         (xStart, xEnd) = plotutils.find_x_range(SessionLog)
         if Debug:
            print "\n\nStart X: **%s**\nEnd X: **%s**\n\n" % (xStart, xEnd)

         PlotYCols = plotutils.get_plot_cols(InitValues['PlotType'])
         if Debug:
            print "\n\nPlotYCols: %s\n\n" % PlotYCols

         if InitValues['PlotType'] == "Temp":
            (y1Start, y1End, RtnMssg) = plotutils.find_y_range(SessionLog, PlotYCols['TempF'])
         else:
            (y1Start, y1End, RtnMssg) = plotutils.find_y_range(SessionLog, PlotYCols['DMM'])

         if Debug:
            print "\n\nSmallest Y1: **%s**\nLargest Y1: **%s** \nMssg: **%s**\n\n" % (y1Start, y1End, RtnMssg)

         InitValues['PlotStart'] = xStart
         InitValues['PlotEnd'] = xEnd
         InitValues['Y1MinVal'] = y1Start
         InitValues['Y1MaxVal'] = y1End
   
         InitValues['PlotPath'] = ParentDir

         if InitValues['PlotType'] == "Temp":
            (y2Start, y2End, RtnMssg) = plotutils.find_y_range(SessionLog, PlotYCols['TempC'])
            if Debug:
               print "\n\nSmallest Y2: **%s**\nLargest Y2: **%s** \nMssg: **%s**\n\n" % (y2Start, y2End, RtnMssg)
            InitValues['Y2MinVal'] = y2Start
            InitValues['Y2MaxVal'] = y2End
            InitValues['Plot2Cols'] = "2:" + str(PlotYCols['TempC'])
            InitValues['Plot1Cols'] = "2:" + str(PlotYCols['TempF'])
         else:
            InitValues['Plot1Cols'] = "2:" + str(PlotYCols['DMM'])

         NewTemplateFileValues = plotutils.set_replaceable_values(PlotPath, SessionTemplate, InitValues)
         (RtnStat, RtnMssg) = plotutils.create_cmd_file(PlotPath, NewTemplateFileValues, InitValues['SessionTemplate'])
         if not RtnStat:
            print "\n\nCreate gnuPlot command file error: **%s**\n\n" % (RtnMssg)
            sys.exit()

         # Ready to go; create the plot file.
         (RtnStat, RtnMssg) = plotutils.create_plot_graph(PlotPath, InitValues['SessionTemplate'])
         if not RtnStat:
            print "\n\nCreate gnuPlot graph file error: \n\n%s\n" % (RtnMssg)
            sys.exit()
         else:
            print "\nSession template %s and graph file %s created " \
                  "sucessfully \nfrom log file %s\n" % \
                  (InitValues['SessionTemplate'],
                  InitValues['OutputGraphName'] + '.png',
                  InitValues['LogFileName'])

            # Design note: which one of these is "correct"?
            # They both work.
            #if 'ImageViewer' in InitValues:
            if 'ImageViewer' in InitValues.keys():
               if len(InitValues['ImageViewer']) > 0:
                  (RtnStat, RtnMssg) = plotutils.open_image_viewer(PlotPath, InitValues['ImageViewer'],
                                                                   InitValues['OutputGraphName'] + '.png')

               if not RtnStat:
                  print "\n\nImage viewer %s command execute error: **%s**\n\n" % \
                        (InitValues['ImageViewer'], RtnMssg)
            #else:
            #   print 'ImageViewer IS NOT defined'


if __name__ == "__main__":
   plot_main()
